const request = require("request");


const login = (userInfo, cb) => {
    var ret = {
        result: -1,
        msg: "登录错误"
    };
    if (userInfo.userType !== "juhe") {
        cb(ret);
        console.error("it's not juhe user");
    } else {
        let url = 'http://www.noatin.com/openapi/validate?uuid=' + userInfo.uuid + '&ticket=' + userInfo.ticket;
        if (userInfo.host === "testeditor.noatin.com") {
            url = 'http://snstest.noatin.com/openapi/validate?uuid=' + userInfo.uuid + '&ticket=' + userInfo.ticket;
        }
        console.log("聚合登录url：" + url);
        request({
            url: url
        }, (error, response, body) => {
            if (error) {
                cb(ret);
            } else {
                // console.log(body);
                body = JSON.parse(body);
                if (body.err_code === 0) {
                    console.log("聚合用户id:" + body.userInfo.uuid);
                    console.log("聚合第三方用户openid:" + body.userInfo.userType + "_" + body.userInfo.id);
                    var userInfo2 = {
                        userType: "juhe",
                        id: "juhe_" + userInfo.uuid,
                        oldUserId: body.userInfo.userType + "_" + body.userInfo.id, //这个字段为了刷新旧用户数据用  以后会删掉         
                        // uuid: userInfo.uuid,
                        ticket: userInfo.ticket,
                        nickname: body.userInfo.uname,
                        verified: true
                        // prop: body.userInfo
                    };

                    // req.session.userInfo = userInfo;
                    ret = {
                        result: 0,
                        msg: userInfo2
                    }
                    cb(ret);
                } else {
                    cb(ret);
                }
            }
        });
    }
};
module.exports.login = login;